import {
  Body,
  Controller,
  HttpException,
  Post,
  Req,
  UploadedFile,
  UseInterceptors,
} from "@nestjs/common";
import { loginData, registerData, forgetData } from "src/dto/user.dto";
import { error, success } from "src/utils/common";
import { UserService } from "./user.service";
import { Request } from "express";
import { FileInterceptor } from "@nestjs/platform-express";
import * as imageType from "image-type";
import { v4 } from "uuid";
import { User } from "src/entity/user.entity";
const mimeTypes = new Set(["jpg", "png", "jpeg", "bmp"]);

@Controller("user")
export class UserController {
  constructor(private userService: UserService) {}

  @Post("/login")
  async login(@Body() loginData: loginData) {
    switch (loginData.type) {
      case "email":
        return await this.userService.loginEmail(loginData);
      case "password":
        return await this.userService.loginPassword(loginData);
      default:
        return error("类型有误");
    }
  }

  @Post("/register")
  async register(@Body() registerData: registerData) {
    const res = await this.userService.register(registerData);
    return res;
  }

  @Post("/forget")
  async foreget(@Body() forgetData: forgetData, @Req() request: Request) {
    const state = await this.userService.forget(
      forgetData,
      request.headers.token as string
    );
    if (state) {
      return success("更新成功");
    } else {
      return error("更新失败", 400);
    }
  }

  @Post("/getMyInfo")
  async getMyInfo(@Req() request: Request) {
    const userInfo: User = request.body.user;
    userInfo.user_creationTime = undefined;
    userInfo.user_password = undefined;
    userInfo.user_status = undefined;
    return success("ok", { user: request.body.user });
  }

  @Post("/updateInfo")
  async updateInfo(@Body() info, @Req() request: Request) {
    const type = info.user_info.hasOwnProperty("user_password") ? true : false;
    const user = Object.assign(info.user, info.user_info);
    await this.userService.updateInfo(
      user,
      type,
      request.headers.token as string
    );
    if (!type) {
      return success("更新成功");
    }
    throw new HttpException({ code: 501, msg: "令牌不存在" }, 200);
  }

  @Post("upload")
  @UseInterceptors(FileInterceptor("file"))
  uploadImage(
    @UploadedFile() file: Express.Multer.File,
    @Req() request: Request
  ) {
    const ret = imageType(file.buffer);
    //限制大小
    if (file.size > 1024 * 1024) {
      throw new HttpException({ code: 601, msg: "文件大小最大为1MB" }, 200);
    }
    //限制文件类型
    if (!ret || !mimeTypes.has(ret.ext)) {
      throw new HttpException(
        { code: 602, msg: "只允许上传jpg、png、jpeg" },
        200
      );
    }

    const data = this.userService.uploadHead(
      file.buffer,
      `${v4()}.${ret.ext}`,
      request.headers.token as string
    );
    if (data) {
      return success("上传成功", { path: data });
    }
    throw new HttpException({ code: 603, msg: "文件生成失败" }, 200);
  }
}
